/*
 *所有关于subcontracting_plan类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*subcontracting_planService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.DbSqlSugar;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using static ATkg.BizAppProject.Services.table_wgjyService;
using System.Globalization;
using DGZImp.Core.EFDbContext;
using Microsoft.Extensions.Configuration;
using static ATkg.BizAppProject.Services.wsz_shebeiService;
using System.DirectoryServices.ActiveDirectory;
using static ATkg.BizAppProject.Services.material_plan_xieService;
using DocumentFormat.OpenXml.Spreadsheet;

namespace ATkg.BizAppProject.Services
{
    public partial class subcontracting_planService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Isubcontracting_planRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public IConfiguration _config;
        public HttpClient client = null;
        public static IHttpClientFactory _httpClientFactory { get; set; }

        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();
        //public ILogger<AmesSyncService> logger { get; set; }

        [ActivatorUtilitiesConstructor]
        public subcontracting_planService(
            Isubcontracting_planRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public async Task<object> get_info_from_daojiao()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };
            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "已取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" }
                };
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "production_type", "=","white" },
                new List<object> { "state", "not in", new List<object> { "cancel", "done" } },
                "|",
                new List<object> { "partner_id", "ilike", "爱科" },
                new List<object> { "partner_id", "ilike", "北方" },
            };
            var qFields = new List<string> {
                "id", "schedule_id", "name", "raw_lot_id","grade","plating","prodcut_spec","product_id","date_planned","date_delivery","product_qty",
                "product_uom","production_type","top_id","state","reality_get_Date","piece_weight","lot_ids","raw_resume_weight","partner_id"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            for (int i = 0; i < res.Count; i++)
            {
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["top_id"][0];
                JArray lot_dis = (JArray)per_["lot_ids"];
                var piece_weight = 0.0;
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> { product_nameid };
                var qFields12 = new List<string> { "tech_user_id", "weight_g" };
                var resp12 = await ames.CallRead("atm.plm.top", qDomain12, qFields12, "");
                var res12 = (JArray)resp12["result"];
                Console.WriteLine(res12);
                string product_name = res12[0]["tech_user_id"][1].ToString();

                if (lot_dis.Count > 0)
                {
                    var id_lot = lot_dis[0];
                    var qDomain1 = new List<object> { id_lot };
                    var qFields1 = new List<string> { "piece_weight" };
                    var resp1 = await ames.CallRead("stock.production.lot", qDomain1, qFields1, "");
                    var res1 = (JArray)resp1["result"];
                    Console.WriteLine(res1);
                    piece_weight = (float)res12[0]["weight_g"] / 1000; ;                    
                    //if()
                }
                var result = Db.Queryable<subcontracting_plan>()  //  
                    .Where(m => m.Lot == per_["name"].ToString())
                    .Select(m => new
                    {
                        m.Lot,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                if (result.Count == 0)
                {
                    var data_3 = new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北京工厂",
                        Jieshou = per_["partner_id"][1].ToString(),
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        IsJB = "",
                        AcptTimeSD = "",
                        PredictDeliveryTime = "",
                        ElecOutputPlan = "",
                        MateIssTime = "",
                        update_data = result_date,
                        ModifyTime = result_date,

                    };

                    final_data_info1.Add(data_3);
                }
                else
                {
                    int rowsAffected = Db.Updateable<subcontracting_plan>()
                    .SetColumns(it => new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北京工厂",
                        Jieshou = per_["partner_id"][1].ToString(),
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        update_data = result_date,
                        ModifyTime = result_date,
                    })
                    .Where(it => it.Lot == per_["name"].ToString()) // 精确条件
                    .ExecuteCommand();
                }

            }

            await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return res;
        }


        public async Task<object> get_info_from_jianbao()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };

            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "已取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" }
                };
            Console.WriteLine("进来了！！！检包·······");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "production_type", "=","final" },
                new List<object> { "state", "not in", new List<object> { "cancel", "done" } },
                "|",
                new List<object> { "partner_id", "ilike", "爱科" },
                new List<object> { "partner_id", "ilike", "北方" },
            };
            var qFields = new List<string> {
                "id", "schedule_id", "name", "raw_lot_id","grade","plating","prodcut_spec","product_id","date_planned","date_delivery","product_qty",
                "product_uom","production_type","top_id","state","reality_get_Date","piece_weight","lot_ids","raw_resume_weight","partner_id"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            for (int i = 0; i < res.Count; i++)
            {
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["top_id"][0];
                JArray lot_dis = (JArray)per_["lot_ids"];
                var piece_weight = 0.0;
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> { product_nameid };
                var qFields12 = new List<string> { "tech_user_id", "weight_g" };
                var resp12 = await ames.CallRead("atm.plm.top", qDomain12, qFields12, "");
                var res12 = (JArray)resp12["result"];
                Console.WriteLine(res12);
                string product_name = res12[0]["tech_user_id"][1].ToString();

                if (lot_dis.Count > 0)
                {
                    var id_lot = lot_dis[0];
                    var qDomain1 = new List<object> { id_lot };
                    var qFields1 = new List<string> { "piece_weight" };
                    var resp1 = await ames.CallRead("stock.production.lot", qDomain1, qFields1, "");
                    var res1 = (JArray)resp1["result"];
                    Console.WriteLine(res1);
                    piece_weight = (float)res12[0]["weight_g"] / 1000;
                    //if()
                }
                var result = Db.Queryable<subcontracting_plan>()  //  
                    .Where(m => m.Lot == per_["name"].ToString())
                    .Select(m => new
                    {
                        m.Lot,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                if (result.Count == 0)
                {
                    var data_3 = new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北京工厂",
                        Jieshou = per_["partner_id"][1].ToString(),
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        IsJB = "",
                        AcptTimeSD = "",
                        PredictDeliveryTime = "",
                        ElecOutputPlan = "",
                        MateIssTime = "",
                        update_data = result_date,
                        ModifyTime = result_date,
                    };

                    final_data_info1.Add(data_3);
                }
                else
                {
                    int rowsAffected = Db.Updateable<subcontracting_plan>()
                    .SetColumns(it => new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北京工厂",
                        Jieshou = per_["partner_id"][1].ToString(),
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        update_data = result_date,
                        ModifyTime = result_date,
                    })
                    .Where(it => it.Lot == per_["name"].ToString()) // 精确条件
                    .ExecuteCommand();
                }

            }

            await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return res;
        }

        public async Task<object> get_db_data()
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            var result = Db.Queryable<subcontracting_plan>()  //  
                .Select(m => m.update_data)               // 选择 update_data 字段
                                                          //.Take(1)                                 // 限制返回 1 条记录
                .ToList();                               // 执行查询并返回列表
            return result;
        }



        public async Task<object> get_info_from_daojiao_ak()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };
            Dictionary<string, string> weituo_JIGONGCH = new Dictionary<string, string>
                {
                    { "DD-04", "北京工厂" },
                    { "DD-09", "北方工厂" },
                };
            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "已取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" }
                };
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Dy123456";
            ames.url = "http://10.7.1.4/jsonrpc";
            ames.db = "sd";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "production_type", "=","white" },
                new List<object> { "state", "not in", new List<object> { "cancel", "done" } },
                "|",
                new List<object> { "partner_id", "ilike", "DD-04" },
                new List<object> { "partner_id", "ilike", "DD-09" }
            };
            var qFields = new List<string> {
                "id", "schedule_id", "name", "raw_lot_id","grade","plating","prodcut_spec","product_id","date_planned","date_delivery","product_qty",
                "product_uom","production_type","top_id","state","reality_get_Date","piece_weight","lot_ids","raw_resume_weight","partner_id"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            for (int i = 0; i < res.Count; i++)
            {
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["top_id"][0];
                JArray lot_dis = (JArray)per_["lot_ids"];
                var piece_weight = 0.0;
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> { product_nameid };
                var qFields12 = new List<string> { "tech_user_id", "weight_g" };
                var resp12 = await ames.CallRead("atm.plm.top", qDomain12, qFields12, "");
                var res12 = (JArray)resp12["result"];
                Console.WriteLine(res12);
                string product_name = res12[0]["tech_user_id"][1].ToString();

                if (lot_dis.Count > 0)
                {
                    var id_lot = lot_dis[0];
                    var qDomain1 = new List<object> { id_lot };
                    var qFields1 = new List<string> { "piece_weight" };
                    var resp1 = await ames.CallRead("stock.production.lot", qDomain1, qFields1, "");
                    var res1 = (JArray)resp1["result"];
                    Console.WriteLine(res1);
                    piece_weight = (float)res12[0]["weight_g"] / 1000;
                    //if()
                }
                var result = Db.Queryable<subcontracting_plan>()  //  
                    .Where(m => m.Lot == per_["name"].ToString())
                    .Select(m => new
                    {
                        m.Lot,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                if (result.Count == 0)
                {
                    var data_3 = new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "爱科工厂",
                        Jieshou = weituo_JIGONGCH[per_["partner_id"][1].ToString()],
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        IsJB = "",
                        AcptTimeSD = "",
                        PredictDeliveryTime = "",
                        ElecOutputPlan = "",
                        MateIssTime = "",
                        update_data = result_date,
                        ModifyTime = result_date,

                    };

                    final_data_info1.Add(data_3);
                }
                else
                {
                    int rowsAffected = Db.Updateable<subcontracting_plan>()
                    .SetColumns(it => new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "爱科工厂",
                        Jieshou = weituo_JIGONGCH[per_["partner_id"][1].ToString()],
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        update_data = result_date,
                        ModifyTime = result_date,
                    })
                    .Where(it => it.Lot == per_["name"].ToString()) // 精确条件
                    .ExecuteCommand();
                }

            }

            await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return res;
        }


        public async Task<object> get_info_from_jianbao_ak()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };
            Dictionary<string, string> weituo_JIGONGCH = new Dictionary<string, string>
                {
                    { "JF-02", "北京工厂" },
                    { "JF-04", "北方工厂" },
                };
            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "已取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" }
                };
            Console.WriteLine("进来了！！！检包·······");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Dy123456";
            ames.url = "http://10.7.1.4/jsonrpc";
            ames.db = "sd";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "production_type", "=","final" },
                new List<object> { "state", "not in", new List<object> { "cancel", "done" } },
                "|",
                new List<object> { "partner_id", "ilike", "JF-02" },
                new List<object> { "partner_id", "ilike", "JF-04" },
            };
            var qFields = new List<string> {
                "id", "schedule_id", "name", "raw_lot_id","grade","plating","prodcut_spec","product_id","date_planned","date_delivery","product_qty",
                "product_uom","production_type","top_id","state","reality_get_Date","piece_weight","lot_ids","raw_resume_weight","partner_id"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("mrp.production", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            for (int i = 0; i < res.Count; i++)
            {
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["top_id"][0];
                JArray lot_dis = (JArray)per_["lot_ids"];
                var piece_weight = 0.0;
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> { product_nameid };
                var qFields12 = new List<string> { "tech_user_id" , "weight_g" };
                var resp12 = await ames.CallRead("atm.plm.top", qDomain12, qFields12, "");
                var res12 = (JArray)resp12["result"];
                Console.WriteLine(res12);
                string product_name = res12[0]["tech_user_id"][1].ToString();
                
                if (lot_dis.Count > 0)
                {
                    var id_lot = lot_dis[0];
                    var qDomain1 = new List<object> { id_lot };
                    var qFields1 = new List<string> { "piece_weight" };
                    var resp1 = await ames.CallRead("stock.production.lot", qDomain1, qFields1, "");
                    var res1 = (JArray)resp1["result"];
                    Console.WriteLine(res1);
                    piece_weight = (float)res12[0]["weight_g"] / 1000;
                    //if()
                }
                var result = Db.Queryable<subcontracting_plan>()  //  
                    .Where(m => m.Lot == per_["name"].ToString())
                    .Select(m => new
                    {
                        m.Lot,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                var jieshou_ = "";
                if (per_["partner_id"][1].ToString().Contains("JF"))
                {
                    jieshou_ = weituo_JIGONGCH[per_["partner_id"][1].ToString()];
                }
                else
                {
                    jieshou_ = per_["partner_id"][1].ToString();
                }
                if (result.Count == 0)
                {
                    var data_3 = new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "爱科工厂",
                        Jieshou = jieshou_,
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        IsJB = "",
                        AcptTimeSD = "",
                        PredictDeliveryTime = "",
                        ElecOutputPlan = "",
                        MateIssTime = "",
                        update_data = result_date,
                        ModifyTime = result_date,
                    };

                    final_data_info1.Add(data_3);
                }
                else
                {
                    int rowsAffected = Db.Updateable<subcontracting_plan>()
                    .SetColumns(it => new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "爱科工厂",
                        Jieshou = jieshou_,
                        OrderPlan = per_["schedule_id"][1].ToString(),
                        product = per_["top_id"][1].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_id"][1].ToString(),
                        XNeng = per_["grade"][1].ToString(),
                        DuCeng = per_["plating"][1].ToString(),
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom"][1].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        update_data = result_date,
                        ModifyTime = result_date,
                    })
                    .Where(it => it.Lot == per_["name"].ToString()) // 精确条件
                    .ExecuteCommand();
                }

            }

            await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return res;
        }



        public async Task<object> get_info_from_daojiao_bf()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };
            Dictionary<string, string> weituo_JIGONGCH = new Dictionary<string, string>
                {
                    { "DD-04", "北京工厂" },
                    { "DD-09", "爱科工厂" },
                };
            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "已取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" }
                };
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                "&",
                new List<object> { "production_type", "=","white" },
                "&",
                new List<object> { "state", "not in", new List<object> { "cancel", "done" } },
                "|",
                new List<object> { "partner_id", "ilike", "空港" },
                new List<object> { "partner_id", "ilike", "爱科" }
            };
            //var qDomain = new List<object> {
            //    "&",
            //    new List<object> { "production_type", "=","white" },
            //    "|",
            //    new List<object> { "partner_id", "ilike", "空港" },
            //    new List<object> { "partner_id", "ilike", "爱科" }
            //};


            var specification = new Dictionary<string, object>
            {
                {"id",new Dictionary<string, object>() },
                {
                    "schedule_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"name", new Dictionary<string, object>() },
                {"raw_lot_name", new Dictionary<string, object>() },
                {
                    "grade", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "plating", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"prodcut_spec", new Dictionary<string, object>() },
                {
                    "product_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"date_planned", new Dictionary<string, object>() },
                {"date_delivery", new Dictionary<string, object>() },
                {"product_qty", new Dictionary<string, object>() },
                {
                    "product_uom_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"production_type",new Dictionary<string, object>() },
                {
                    "top_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"state", new Dictionary<string, object>() },
                {
                    "lot_ids", new List<object>
                    {
                       new Dictionary<string, object>
                        {
                            { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                        }
                    }
                },
                {"raw_resume_weight",new Dictionary<string,object>() },
                {
                    "partner_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                }, //reality_get_Date
                {"reality_get_Date", new Dictionary<string, object>() },

             };
            var qFields = new List<string> {
                "id", "schedule_id", "name", "raw_lot_id","grade","plating","prodcut_spec","product_id","date_planned","date_delivery","product_qty",
                "product_uom","production_type","top_id","state","reality_get_Date","piece_weight","lot_ids","raw_resume_weight","partner_id"
            };
            var result = new Dictionary<string, object>
            {
                { "domain", qDomain },
                { "specification", specification }
            };

            var resp = await ames.Get_web_search_read("mrp.production", result);
            Console.WriteLine(resp);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];
            Console.WriteLine(record);
            var res = record;
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            for (int i = 0; i < res.Count; i++)
            {
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["top_id"]["id"]; ;
                JArray lot_dis = (JArray)per_["lot_ids"];
                var piece_weight = 0.0;
                //var id_lot = lot_dis[0];

                var qDomain12 = new List<object> { new List<object> { product_nameid } };
                var specification_tec = new Dictionary<string, object>
                {
                    {"id",new Dictionary<string, object>() },
                    {
                        "tech_user_id", new Dictionary<string, object>
                        {
                            { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                        }
                    },
                    {"weight_g", new Dictionary<string, object>() }, 
                };
                var result_in = new Dictionary<string, object>
                {
                    { "specification", specification_tec }
                };
                
                var resp12 = await ames.Get_web_read_all("atm.plm.top", product_nameid, result_in);
                var res12 = (JArray)resp12["result"];
                Console.WriteLine(res12);
                string product_name = res12[0]["tech_user_id"]["display_name"].ToString(); 
                piece_weight = (float)res12[0]["weight_g"] / 1000;
                Console.WriteLine(piece_weight);

                if (lot_dis.Count > 0)
                {
                    int id_lot = (int)lot_dis[0];
                    var specification_weight = new Dictionary<string, object>
                    {
                        {"id",new Dictionary<string, object>() },
                        {
                            "piece_weight", new Dictionary<string, object>()
                        }
                    };
                    var result_weight = new Dictionary<string, object>
                    {
                        { "specification", specification_weight }
                    };
                    var resp_weg = await ames.Get_web_read_all("stock.lot", id_lot, result_weight);
                    var res_weg = (JArray)resp_weg["result"];
                    Console.WriteLine(res_weg);

                    //if()
                }
                var result_ = Db.Queryable<subcontracting_plan>()  //  
                    .Where(m => m.Lot == per_["name"].ToString())
                    .Select(m => new
                    {
                        m.Lot,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                Console.WriteLine(result_.Count);
                Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                if (result_.Count == 0)
                {
                    var data_3 = new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北方工厂",
                        Jieshou = per_["partner_id"]["display_name"].ToString(),
                        OrderPlan = per_["schedule_id"]["display_name"].ToString(),
                        product = per_["top_id"]["display_name"].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_name"].ToString(),
                        XNeng = per_["grade"]["display_name"].ToString(),
                        DuCeng = per_["plating"]["display_name"].ToString(),//
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom_id"]["display_name"].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        IsJB = "",
                        AcptTimeSD = "",
                        PredictDeliveryTime = "",
                        ElecOutputPlan = "",
                        MateIssTime = "",
                        update_data = result_date,
                        ModifyTime = result_date,

                    };

                    final_data_info1.Add(data_3);
                }
                else
                {
                    Console.WriteLine("lens11111111111111111");
                    int rowsAffected = Db.Updateable<subcontracting_plan>()
                    .SetColumns(it => new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北方工厂",
                        Jieshou = per_["partner_id"]["display_name"].ToString(),
                        OrderPlan = per_["schedule_id"]["display_name"].ToString(),
                        product = per_["top_id"]["display_name"].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_name"].ToString(),
                        XNeng = per_["grade"]["display_name"].ToString(),
                        DuCeng = per_["plating"]["display_name"].ToString(),//
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom_id"]["display_name"].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        update_data = result_date,
                        ModifyTime = result_date,
                    })
                    .Where(it => it.Lot == per_["name"].ToString()) // 精确条件
                    .ExecuteCommand();
                }

            }

            await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return final_data_info1;
        }


        public async Task<object> get_info_from_jianbao_bf()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Dictionary<string, string> weituo = new Dictionary<string, string>
                {
                    { "white", "倒角电镀" },
                    { "final", "检包" },
                };
            Dictionary<string, string> weituo_JIGONGCH = new Dictionary<string, string>
                {
                    { "JF-02", "北京工厂" },
                    { "JF-04", "北方工厂" },
                };
            Dictionary<string, string> state = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "cancel", "已取消" },
                    { "confirmed", "等待原材料" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" }
                };
            Console.WriteLine("进来了！！！检包·······");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";


            //var typeArray = new[] { "final" };


            var qDomain = new List<object> {
                "&",
                new List<object> { "production_type", "=","final" },
                "&",
                new List<object> { "state", "not in", new List<object> { "cancel", "done" } },
                "|",
                new List<object> { "partner_id", "ilike", "空港" },
                new List<object> { "partner_id", "ilike", "爱科" }
            };
            //var qDomain = new List<object> {
            //    "&",
            //    new List<object> { "production_type", "=","final" },
            //    "|",
            //    new List<object> { "partner_id", "ilike", "空港" },
            //    new List<object> { "partner_id", "ilike", "爱科" }
            //};
            var specification = new Dictionary<string, object>
            {
                {"id",new Dictionary<string, object>() },
                {
                    "schedule_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"name", new Dictionary<string, object>() },
                {"raw_lot_name", new Dictionary<string, object>() },
                {
                    "grade", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "plating", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"prodcut_spec", new Dictionary<string, object>() },
                {
                    "product_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"date_planned", new Dictionary<string, object>() },
                {"date_delivery", new Dictionary<string, object>() },
                {"product_qty", new Dictionary<string, object>() },
                {
                    "product_uom_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"production_type",new Dictionary<string, object>() },
                {
                    "top_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {"state", new Dictionary<string, object>() },
                {
                    "lot_ids", new List<object>
                    {
                       new Dictionary<string, object>
                        {
                            { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                        }
                    }
                },
                {"raw_resume_weight",new Dictionary<string,object>() },
                {
                    "partner_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                }, //reality_get_Date
                {"reality_get_Date", new Dictionary<string, object>() },

             };
            var qFields = new List<string> {
                "id", "schedule_id", "name", "raw_lot_id","grade","plating","prodcut_spec","product_id","date_planned","date_delivery","product_qty",
                "product_uom","production_type","top_id","state","reality_get_Date","piece_weight","lot_ids","raw_resume_weight","partner_id"
            };
            var result = new Dictionary<string, object>
            {
                { "domain", qDomain },
                { "specification", specification }
            };
            var qPage = new
            { };
            var resp = await ames.Get_web_search_read("mrp.production", result);
            Console.WriteLine(resp);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];
            Console.WriteLine(record);
            var res = record;
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            for (int i = 0; i < res.Count; i++)
            {
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["top_id"]["id"]; ;
                JArray lot_dis = (JArray)per_["lot_ids"];
                var piece_weight = 0.0;
                //var id_lot = lot_dis[0];

                var qDomain12 = new List<object> { new List<object> { product_nameid } };
                var specification_tec = new Dictionary<string, object>
                {
                    {"id",new Dictionary<string, object>() },
                    {
                        "tech_user_id", new Dictionary<string, object>
                        {
                            { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                        }
                    },
                    {"weight_g", new Dictionary<string, object>() },
                };
                var result_in = new Dictionary<string, object>
                {
                    { "specification", specification_tec }
                };

                var resp12 = await ames.Get_web_read_all("atm.plm.top", product_nameid, result_in);
                var res12 = (JArray)resp12["result"];
                Console.WriteLine(res12);
                string product_name = res12[0]["tech_user_id"]["display_name"].ToString();
                piece_weight = (float)res12[0]["weight_g"] / 1000;
                Console.WriteLine(piece_weight);

                if (lot_dis.Count > 0)
                {
                    int id_lot = (int)lot_dis[0];
                    var specification_weight = new Dictionary<string, object>
                    {
                        {"id",new Dictionary<string, object>() },
                        {
                            "piece_weight", new Dictionary<string, object>()
                        }
                    };
                    var result_weight = new Dictionary<string, object>
                    {
                        { "specification", specification_weight }
                    };
                    var resp_weg = await ames.Get_web_read_all("stock.lot", id_lot, result_weight);
                    var res_weg = (JArray)resp_weg["result"];
                    Console.WriteLine(res_weg);

                    //if()
                }
                var result_ = Db.Queryable<subcontracting_plan>()  //  
                    .Where(m => m.Lot == per_["name"].ToString())
                    .Select(m => new
                    {
                        m.Lot,
                    })               // 选择 update_data 字段
                    .ToList();                               // 执行查询并返回列表
                Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                Console.WriteLine(result_.Count);
                Console.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                if (result_.Count == 0)
                {
                    var data_3 = new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北方工厂",
                        Jieshou = per_["partner_id"]["display_name"].ToString(),
                        OrderPlan = per_["schedule_id"]["display_name"].ToString(),
                        product = per_["top_id"]["display_name"].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_name"].ToString(),
                        XNeng = per_["grade"]["display_name"].ToString(),
                        DuCeng = per_["plating"]["display_name"].ToString(),//
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom_id"]["display_name"].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        IsJB = "",
                        AcptTimeSD = "",
                        PredictDeliveryTime = "",
                        ElecOutputPlan = "",
                        MateIssTime = "",
                        update_data = result_date,
                        ModifyTime = result_date,

                    };

                    final_data_info1.Add(data_3);
                }
                else
                {
                    Console.WriteLine("lens11111111111111111");
                    int rowsAffected = Db.Updateable<subcontracting_plan>()
                    .SetColumns(it => new subcontracting_plan
                    {
                        FachuTime = per_["reality_get_Date"].ToString() != "False" ? per_["reality_get_Date"].ToString() : "",
                        LLDanWei = "北方工厂",
                        Jieshou = per_["partner_id"]["display_name"].ToString(),
                        OrderPlan = per_["schedule_id"]["display_name"].ToString(),
                        product = per_["top_id"]["display_name"].ToString(),
                        Lot = per_["name"].ToString(),
                        TlLot = per_["raw_lot_name"].ToString(),
                        XNeng = per_["grade"]["display_name"].ToString(),
                        DuCeng = per_["plating"]["display_name"].ToString(),//
                        ProductGre = per_["prodcut_spec"].ToString(),
                        ProgPartner = product_name.ToString(),
                        PlanDate = per_["date_planned"].ToString(),
                        ReqDate = per_["date_delivery"].ToString(),
                        Qty = per_["product_qty"].ToString(),
                        PerWeight = piece_weight.ToString(),
                        SendQty = per_["raw_resume_weight"].ToString(),
                        Unit = per_["product_uom_id"]["display_name"].ToString(),
                        OrderWT = weituo[per_["production_type"].ToString()],
                        Statues = state[per_["state"].ToString()],
                        update_data = result_date,
                        ModifyTime = result_date,
                    })
                    .Where(it => it.Lot == per_["name"].ToString()) // 精确条件
                    .ExecuteCommand();
                }

            }

            await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return final_data_info1;
        }



        public async Task<object> get_yf_from_mes(string proname)
        {            
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "order_type", "=","product" },
                new List<object> { "original_product_code", "ilike", proname }
            };
            var qFields = new List<string> {
                "id", "name", "partner_blueprint_no"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            var all_in_list = new List<object>();
            for (int i = 0; i < res.Count; i++)
            {
                var per_info_list = new List<object>();
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["id"];
                Console.WriteLine(product_nameid);
                Console.WriteLine(per_["name"].ToString());
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> { 
                    new List<object> { "top_id", "=", product_nameid },
                };
                var qFields12 = new List<string> { "name", "final_qty_available", "manufacturing_incoming_final_qty" };

                var qPage12 = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai", no_scrap = true }, limit = 10000, offset = 0 };

                var resp12 = await ames.Get_info_gzd("product.product", qDomain12, qFields12, qPage12);
                var originalList = (JArray)resp12["result"];
                Console.WriteLine(originalList);
                Console.WriteLine("LLLLLL");

                per_info_list.Add(per_["name"].ToString());  //新增


                // 辅助方法：判断字符串中第一个"/"之后的内容是否包含"N"
                bool HasNAfterFirstSlash(string name)
                {
                    int firstSlashIndex = name.IndexOf('/');
                    if (firstSlashIndex == -1)
                        return false; // 不含"/"，自然没有第一个"/"后的N
                                      // 截取第一个"/"之后的内容，判断是否含"N"
                    string partAfterFirstSlash = name.Substring(firstSlashIndex + 1);
                    return partAfterFirstSlash.Contains("N");
                }

                // 第一步：生成result列表（排除条件更新为：第一个"/"后含N的项）
                var result = originalList
                    .Where(item =>
                        !item["name"].ToString().Contains("废料")  // 排除废料
                        && !HasNAfterFirstSlash(item["name"].ToString())  // 排除第一个"/"后含N的项
                        && !item["name"].ToString().Contains("细粉") // 排除细粉
                        && !item["name"].ToString().Contains("氢破") // 排除细粉
                        && !item["name"].ToString().Contains("气流磨") // 排除细粉
                    )
                    .Select(item =>
                    {
                        string name = item["name"].ToString();
                        int slashCount = name.Count(c => c == '/');
                        if (slashCount > 1)
                        {
                            int firstSlash = name.IndexOf('/');
                            int secondSlash = name.IndexOf('/', firstSlash + 1);
                            return secondSlash != -1 ? name.Substring(0, secondSlash) : name;
                        }
                        return name;
                    })
                    .Distinct()
                    .ToList();

                // 第二步：为每个result元素计算在库和在线数量
                var resultWithQuantities = new List<Dictionary<string, object>>();
                foreach (var resItem in result)
                {
                    bool hasSlash = resItem.Contains("/");

                    if (hasSlash)
                    {
                        // 特殊处理：含"毛坯"的result项，合并压坯数据
                        if (resItem.Contains("毛坯"))
                        {
                            // 收集所有压坯相关数据（排除废料、第一个/后含N、细粉）
                            var pressedItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString().Contains("压坯")
                                )
                                .ToList();
                            // 压坯总和：final_qty_available + manufacturing_incoming_final_qty
                            double pressedSum = pressedItems.Sum(item =>
                                (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                            // 毛坯自身数据
                            var blankItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString() == resItem  // 完全匹配毛坯项
                                )
                                .ToList();
                            // 毛坯在库数量：自身final_qty_available
                            int blankStock = blankItems.Sum(item => (int)item["final_qty_available"]);
                            // 毛坯在线补充：自身manufacturing_incoming_final_qty
                            double blankManufacturing = blankItems.Sum(item => (double)item["manufacturing_incoming_final_qty"]);

                            // 最终在线数量 = 压坯总和 + 毛坯manufacturing
                            double finalOnline = pressedSum + blankManufacturing;

                            resultWithQuantities.Add(new Dictionary<string, object>
                    {
                        { "名称", resItem },
                        { "在库数量", blankStock },
                        { "在线数量", finalOnline },
                        { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                        { "产品代码", per_["name"].ToString() }
                    });
                        }
                        else
                        {
                            // 含"/"但不含"毛坯"的项，按规则计算
                            var relatedItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString().Contains(resItem)
                                )
                                .ToList();

                            var containsButNotEqual = relatedItems
                                .Where(item => item["name"].ToString() != resItem)
                                .ToList();
                            double onlineFromCondition1 = containsButNotEqual.Sum(item =>
                                (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                            var exactlyEqual = relatedItems
                                .FirstOrDefault(item => item["name"].ToString() == resItem);
                            int stockQuantity = exactlyEqual != null ? (int)exactlyEqual["final_qty_available"] : 0;
                            double manufacturingIncoming = exactlyEqual != null ? (double)exactlyEqual["manufacturing_incoming_final_qty"] : 0;

                            double finalOnlineQuantity = onlineFromCondition1 + manufacturingIncoming;

                            resultWithQuantities.Add(new Dictionary<string, object>
                    {
                        { "名称", resItem },
                        { "在库数量", stockQuantity },
                        { "在线数量", finalOnlineQuantity },
                        { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                        { "产品代码", per_["name"].ToString() }
                    });
                        }
                    }
                    else
                    {
                        // 不含"/"的项，处理含N的数据（仅统计第一个"/"后含N的项）
                        var itemsWithN = originalList
                            .Where(item =>
                                !item["name"].ToString().Contains("废料")
                                && !item["name"].ToString().Contains("细粉")
                                && HasNAfterFirstSlash(item["name"].ToString())  // 仅第一个"/"后含N的项
                                && item["name"].ToString().Contains(resItem)  // 与当前resItem相关
                            )
                            .ToList();
                        double sumWithN = itemsWithN.Sum(item =>
                            (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                        var itemsWithoutSlashAndN = originalList
                            .Where(item =>
                                !item["name"].ToString().Contains("废料")
                                && !HasNAfterFirstSlash(item["name"].ToString())
                                && !item["name"].ToString().Contains("细粉")
                                && item["name"].ToString() == resItem
                            )
                            .ToList();
                        double onlineQuantity = sumWithN + itemsWithoutSlashAndN.Sum(item => (double)item["manufacturing_incoming_final_qty"]);
                        int stockQuantity = itemsWithoutSlashAndN.Sum(item => (int)item["final_qty_available"]);

                        resultWithQuantities.Add(new Dictionary<string, object>
                {
                    { "名称", resItem },
                    { "在库数量", stockQuantity },
                    { "在线数量", onlineQuantity },
                    { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                    { "产品代码", per_["name"].ToString() }
                });
                    }
                }
                all_in_list.Add(resultWithQuantities);
            }

            //await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return all_in_list;
        }


        public async Task<object> get_yf_from_mes_ak(string proname)
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Dy123456";
            ames.url = "http://10.7.1.4/jsonrpc";
            ames.db = "sd";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "order_type", "=","product" },
                new List<object> { "original_product_code", "ilike", proname }
            };
            var qFields = new List<string> {
                "id", "name","partner_blueprint_no"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            var all_in_list = new List<object>();
            for (int i = 0; i < res.Count; i++)
            {
                var per_info_list = new List<object>();
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["id"];
                Console.WriteLine(product_nameid);
                Console.WriteLine(per_["name"].ToString());
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> {
                    new List<object> { "top_id", "=", product_nameid },
                };
                var qFields12 = new List<string> { "name", "final_qty_available", "manufacturing_incoming_final_qty" };

                var qPage12 = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai", no_scrap = true }, limit = 10000, offset = 0 };

                var resp12 = await ames.Get_info_gzd("product.product", qDomain12, qFields12, qPage12);
                var originalList = (JArray)resp12["result"];
                Console.WriteLine(originalList);
                Console.WriteLine("LLLLLL");

                per_info_list.Add(per_["name"].ToString());  //新增


                // 辅助方法：判断字符串中第一个"/"之后的内容是否包含"N"
                bool HasNAfterFirstSlash(string name)
                {
                    int firstSlashIndex = name.IndexOf('/');
                    if (firstSlashIndex == -1)
                        return false; // 不含"/"，自然没有第一个"/"后的N
                                      // 截取第一个"/"之后的内容，判断是否含"N"
                    string partAfterFirstSlash = name.Substring(firstSlashIndex + 1);
                    return partAfterFirstSlash.Contains("N");
                }

                // 第一步：生成result列表（排除条件更新为：第一个"/"后含N的项）
                var result = originalList
                    .Where(item =>
                        !item["name"].ToString().Contains("废料")  // 排除废料
                        && !HasNAfterFirstSlash(item["name"].ToString())  // 排除第一个"/"后含N的项
                        && !item["name"].ToString().Contains("细粉") // 排除细粉
                         && !item["name"].ToString().Contains("压坯") // 排除细粉
                    )
                    .Select(item =>
                    {
                        string name = item["name"].ToString();
                        int slashCount = name.Count(c => c == '/');
                        if (slashCount > 1)
                        {
                            int firstSlash = name.IndexOf('/');
                            int secondSlash = name.IndexOf('/', firstSlash + 1);
                            return secondSlash != -1 ? name.Substring(0, secondSlash) : name;
                        }
                        return name;
                    })
                    .Distinct()
                    .ToList();

                // 第二步：为每个result元素计算在库和在线数量
                var resultWithQuantities = new List<Dictionary<string, object>>();
                foreach (var resItem in result)
                {
                    bool hasSlash = resItem.Contains("/");

                    if (hasSlash)
                    {
                        // 特殊处理：含"毛坯"的result项，合并压坯数据
                        if (resItem.Contains("毛坯"))
                        {
                            // 收集所有压坯相关数据（排除废料、第一个/后含N、细粉）
                            var pressedItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString().Contains("压坯")
                                )
                                .ToList();
                            // 压坯总和：final_qty_available + manufacturing_incoming_final_qty
                            double pressedSum = pressedItems.Sum(item =>
                                (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                            // 毛坯自身数据
                            var blankItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString() == resItem  // 完全匹配毛坯项
                                )
                                .ToList();
                            // 毛坯在库数量：自身final_qty_available
                            int blankStock = blankItems.Sum(item => (int)item["final_qty_available"]);
                            // 毛坯在线补充：自身manufacturing_incoming_final_qty
                            double blankManufacturing = blankItems.Sum(item => (double)item["manufacturing_incoming_final_qty"]);

                            // 最终在线数量 = 压坯总和 + 毛坯manufacturing
                            double finalOnline = pressedSum + blankManufacturing;

                            resultWithQuantities.Add(new Dictionary<string, object>
                    {
                        { "名称", resItem },
                        { "在库数量", blankStock },
                        { "在线数量", finalOnline },
                        { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                        { "产品代码", per_["name"].ToString() }
                    });
                        }
                        else
                        {
                            // 含"/"但不含"毛坯"的项，按规则计算
                            var relatedItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString().Contains(resItem)
                                )
                                .ToList();

                            var containsButNotEqual = relatedItems
                                .Where(item => item["name"].ToString() != resItem)
                                .ToList();
                            double onlineFromCondition1 = containsButNotEqual.Sum(item =>
                                (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                            var exactlyEqual = relatedItems
                                .FirstOrDefault(item => item["name"].ToString() == resItem);
                            int stockQuantity = exactlyEqual != null ? (int)exactlyEqual["final_qty_available"] : 0;
                            double manufacturingIncoming = exactlyEqual != null ? (double)exactlyEqual["manufacturing_incoming_final_qty"] : 0;

                            double finalOnlineQuantity = onlineFromCondition1 + manufacturingIncoming;

                            resultWithQuantities.Add(new Dictionary<string, object>
                    {
                        { "名称", resItem },
                        { "在库数量", stockQuantity },
                        { "在线数量", finalOnlineQuantity },
                        { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                        { "产品代码", per_["name"].ToString() }
                    });
                        }
                    }
                    else
                    {
                        // 不含"/"的项，处理含N的数据（仅统计第一个"/"后含N的项）
                        var itemsWithN = originalList
                            .Where(item =>
                                !item["name"].ToString().Contains("废料")
                                && !item["name"].ToString().Contains("细粉")
                                && HasNAfterFirstSlash(item["name"].ToString())  // 仅第一个"/"后含N的项
                                && item["name"].ToString().Contains(resItem)  // 与当前resItem相关
                            )
                            .ToList();
                        double sumWithN = itemsWithN.Sum(item =>
                            (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                        var itemsWithoutSlashAndN = originalList
                            .Where(item =>
                                !item["name"].ToString().Contains("废料")
                                && !HasNAfterFirstSlash(item["name"].ToString())
                                && !item["name"].ToString().Contains("细粉")
                                && item["name"].ToString() == resItem
                            )
                            .ToList();
                        double onlineQuantity = sumWithN + itemsWithoutSlashAndN.Sum(item => (double)item["manufacturing_incoming_final_qty"]);
                        int stockQuantity = itemsWithoutSlashAndN.Sum(item => (int)item["final_qty_available"]);

                        resultWithQuantities.Add(new Dictionary<string, object>
                {
                    { "名称", resItem },
                    { "在库数量", stockQuantity },
                    { "在线数量", onlineQuantity },
                    { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                    { "产品代码", per_["name"].ToString() }
                });
                    }
                }
                all_in_list.Add(resultWithQuantities);
            }

            //await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return all_in_list;
        }



        public async Task<object> get_yf_from_mes_bf(string proname)
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";

            //var typeArray = new[] { "final" };

            var qDomain = new List<object> {
                new List<object> { "original_product_code", "ilike", proname }
            };
            var qFields = new List<string> {
                "id", "name","partner_blueprint_no"
            };
            var qPage = new
            { };
            var resp = await ames.Get_info_gzd("atm.plm.top", qDomain, qFields, qPage);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var res = (JArray)resp["result"];
            Console.WriteLine(res.Count);
            if (res == null || res.Count <= 0)
            {
                return 0;
            }
            //List<SteelName> list_out_o = new List<SteelName>();
            var final_data_info1 = new List<subcontracting_plan>();
            var all_in_list = new List<object>();
            for (int i = 0; i < res.Count; i++)
            {
                var per_info_list = new List<object>();
                Console.WriteLine(res[i]);
                var per_ = res[i];
                int product_nameid = (int)per_["id"];
                Console.WriteLine(product_nameid);
                Console.WriteLine(per_["name"].ToString());
                //var id_lot = lot_dis[0];
                var qDomain12 = new List<object> {
                    new List<object> { "top_id", "=", product_nameid },
                };
                var qFields12 = new List<string> { "name", "final_qty_available", "manufacturing_incoming_final_qty" };

                //var qPage12 = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai", no_scrap = true }, limit = 10000, offset = 0 };
                var qPage12 = new { context = new { lang = "zh_CN", tz = "Asia/Shanghai", no_scrap = true }, limit = 10000, offset = 0 };

                var resp12 = await ames.Get_info_gzd("product.product", qDomain12, qFields12, qPage12);
                var originalList = (JArray)resp12["result"];
                Console.WriteLine(originalList);
                Console.WriteLine("LLLLLL");

                per_info_list.Add(per_["name"].ToString());  //新增


                // 辅助方法：判断字符串中第一个"/"之后的内容是否包含"N"
                bool HasNAfterFirstSlash(string name)
                {
                    int firstSlashIndex = name.IndexOf('/');
                    if (firstSlashIndex == -1)
                        return false; // 不含"/"，自然没有第一个"/"后的N
                                      // 截取第一个"/"之后的内容，判断是否含"N"
                    string partAfterFirstSlash = name.Substring(firstSlashIndex + 1);
                    return partAfterFirstSlash.Contains("N");
                }

                // 第一步：生成result列表（排除条件更新为：第一个"/"后含N的项）
                var result = originalList
                    .Where(item =>
                        !item["name"].ToString().Contains("废料")  // 排除废料
                        && !HasNAfterFirstSlash(item["name"].ToString())  // 排除第一个"/"后含N的项
                        && !item["name"].ToString().Contains("细粉") // 排除细粉
                    )
                    .Select(item =>
                    {
                        string name = item["name"].ToString();
                        int slashCount = name.Count(c => c == '/');
                        if (slashCount > 1)
                        {
                            int firstSlash = name.IndexOf('/');
                            int secondSlash = name.IndexOf('/', firstSlash + 1);
                            return secondSlash != -1 ? name.Substring(0, secondSlash) : name;
                        }
                        return name;
                    })
                    .Distinct()
                    .ToList();

                // 第二步：为每个result元素计算在库和在线数量
                var resultWithQuantities = new List<Dictionary<string, object>>();
                foreach (var resItem in result)
                {
                    bool hasSlash = resItem.Contains("/");

                    if (hasSlash)
                    {
                        // 特殊处理：含"毛坯"的result项，合并压坯数据
                        if (resItem.Contains("毛坯"))
                        {
                            // 收集所有压坯相关数据（排除废料、第一个/后含N、细粉）
                            var pressedItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString().Contains("压坯")
                                )
                                .ToList();
                            // 压坯总和：final_qty_available + manufacturing_incoming_final_qty
                            double pressedSum = pressedItems.Sum(item =>
                                (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                            // 毛坯自身数据
                            var blankItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString() == resItem  // 完全匹配毛坯项
                                )
                                .ToList();
                            // 毛坯在库数量：自身final_qty_available
                            int blankStock = blankItems.Sum(item => (int)item["final_qty_available"]);
                            // 毛坯在线补充：自身manufacturing_incoming_final_qty
                            double blankManufacturing = blankItems.Sum(item => (double)item["manufacturing_incoming_final_qty"]);

                            // 最终在线数量 = 压坯总和 + 毛坯manufacturing
                            double finalOnline = pressedSum + blankManufacturing;

                            resultWithQuantities.Add(new Dictionary<string, object>
                    {
                        { "名称", resItem },
                        { "在库数量", blankStock },
                        { "在线数量", finalOnline },
                        { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                        { "产品代码", per_["name"].ToString() }
                    });
                        }
                        else
                        {
                            // 含"/"但不含"毛坯"的项，按规则计算
                            var relatedItems = originalList
                                .Where(item =>
                                    !item["name"].ToString().Contains("废料")
                                    && !HasNAfterFirstSlash(item["name"].ToString())
                                    && !item["name"].ToString().Contains("细粉")
                                    && item["name"].ToString().Contains(resItem)
                                )
                                .ToList();

                            var containsButNotEqual = relatedItems
                                .Where(item => item["name"].ToString() != resItem)
                                .ToList();
                            double onlineFromCondition1 = containsButNotEqual.Sum(item =>
                                (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                            var exactlyEqual = relatedItems
                                .FirstOrDefault(item => item["name"].ToString() == resItem);
                            int stockQuantity = exactlyEqual != null ? (int)exactlyEqual["final_qty_available"] : 0;
                            double manufacturingIncoming = exactlyEqual != null ? (double)exactlyEqual["manufacturing_incoming_final_qty"] : 0;

                            double finalOnlineQuantity = onlineFromCondition1 + manufacturingIncoming;

                            resultWithQuantities.Add(new Dictionary<string, object>
                    {
                        { "名称", resItem },
                        { "在库数量", stockQuantity },
                        { "在线数量", finalOnlineQuantity },
                        { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                        { "产品代码", per_["name"].ToString() }
                    });
                        }
                    }
                    else
                    {
                        // 不含"/"的项，处理含N的数据（仅统计第一个"/"后含N的项）
                        var itemsWithN = originalList
                            .Where(item =>
                                !item["name"].ToString().Contains("废料")
                                && !item["name"].ToString().Contains("细粉")
                                && HasNAfterFirstSlash(item["name"].ToString())  // 仅第一个"/"后含N的项
                                && item["name"].ToString().Contains(resItem)  // 与当前resItem相关
                            )
                            .ToList();
                        double sumWithN = itemsWithN.Sum(item =>
                            (int)item["final_qty_available"] + (double)item["manufacturing_incoming_final_qty"]);

                        var itemsWithoutSlashAndN = originalList
                            .Where(item =>
                                !item["name"].ToString().Contains("废料")
                                && !HasNAfterFirstSlash(item["name"].ToString())
                                && !item["name"].ToString().Contains("细粉")
                                && item["name"].ToString() == resItem
                            )
                            .ToList();
                        double onlineQuantity = sumWithN + itemsWithoutSlashAndN.Sum(item => (double)item["manufacturing_incoming_final_qty"]);
                        int stockQuantity = itemsWithoutSlashAndN.Sum(item => (int)item["final_qty_available"]);

                        resultWithQuantities.Add(new Dictionary<string, object>
                {
                    { "名称", resItem },
                    { "在库数量", stockQuantity },
                    { "在线数量", onlineQuantity },
                    { "客户图纸号", per_["partner_blueprint_no"].ToString() },
                    { "产品代码", per_["name"].ToString() }
                });
                    }
                }
                all_in_list.Add(resultWithQuantities);
            }

            //await Db.DoInsertAsync<subcontracting_plan>(final_data_info1);

            return all_in_list;
        }


    }
}
